package com.netposa.kafka;

import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 消费者简单测试(单线程获取消费数据)
 *
 * @author lhy
 * @date 2018.10.09
 */
public class ConsumerThread extends Thread {

    //消费者连接
    private final ConsumerConnector consumer;
    // 要消费的话题
    private final String topic;

    private boolean flag = true;

    public ConsumerThread(String topic) {
        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(createConsumerConfig());
        this.topic = topic;
    }

    //配置相关信息
    private static ConsumerConfig createConsumerConfig() {

        Properties props = new Properties();

        //zookeeper 配置，单节点
        props.put("zookeeper.connect", "192.168.43.121:2181");

        //group 代表一个消费组
        props.put("group.id", "0");

        // 配置zookeeper连接超时时间
        props.put("zookeeper.session.timeout.ms", "10000");

        //zk同步时间
        props.put("zookeeper.sync.time.ms", "200");

        //自动提交间隔时间
        props.put("auto.commit.interval.ms", "1000");

        return new ConsumerConfig(props);
    }


    public void run() {
            Map<String, Integer> topickMap = new HashMap<String, Integer>();
            topickMap.put(topic, 1);
            Map<String, List<KafkaStream<byte[], byte[]>>> streamMap = consumer.createMessageStreams(topickMap);
            KafkaStream<byte[], byte[]> stream = streamMap.get(topic).get(0);
            ConsumerIterator<byte[], byte[]> it = stream.iterator();
            System.out.println("*********Kafka开始消费********");
            while (flag) {

                if (it.hasNext()) {
                    //打印得到的消息
                    System.err.println("it.next().offset())"+it.next().offset()+Thread.currentThread() + " get kafka data:" + new String(it.next().message()));
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    public void flagChange() {
        flag = false;
    }

    public static void main(String[] args) {
        ConsumerThread consumerThread = new ConsumerThread("test");
        consumerThread.start();
    }

}
